package com.sangmo.fts.process.factoring.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.boot.framework.plugin.dataview.crud.service.BaseViewService;
import com.sangmo.boot.framework.plugin.dataview.data.IDataViewRepo;
import com.sangmo.fts.basic.model.Company;
import com.sangmo.fts.basic.service.CompanyService;
import com.sangmo.fts.common.authority.service.AuthorityEntityService;
import com.sangmo.fts.process.factoring.interfaces.FfLoanCreation;
import com.sangmo.fts.process.factoring.model.FfContract;
import com.sangmo.fts.process.factoring.model.FfLoan;
import com.sangmo.fts.process.factoring.model.FfWaybill;
import com.sangmo.fts.process.factoring.repo.FfLoanRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
@Transactional
public class FfLoanEntityService extends AuthorityEntityService<FfLoan> {

    @Autowired
    private FfLoanRepo ffLoanRepo;

    @Autowired
    private FfContractService ffContractService;

    @Autowired
    private FfWaybillService ffWaybillService;

    @Autowired
    private CompanyService companyService;

    @Override
    protected IDataViewRepo<FfLoan> getRepo() {
        return ffLoanRepo;
    }

    @Override
    protected void onCreate(FfLoan entity, Object bo) {
        super.onCreate(entity, bo);
        FfLoanCreation creation = (FfLoanCreation) bo;
        Company company = companyService.get(creation.getApplyId());
        BigDecimal rate = calcRate(company, creation.getDuration());
        entity.setRate(rate);
        entity.setBankId(company.getBankId());
        FfContract contract = ffContractService.get(creation.getContractId());
        FfWaybill waybill = ffWaybillService.findByContractId(contract.getId());
        entity.setWaybillId(waybill.getId());
        entity.setSubDebtor(contract.getBuyerId());
        entity.setContractAmount(ffContractService.calculateContractAmount(creation.getContractId()));
    }

    @Override
    protected void onDelete(FfLoan entity) {
        super.onDelete(entity);
        if (!FfLoan.States.ACCEPTING.equals(entity.getState())) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.ffLoan.remove.permit.disabled");
        }
    }

    private BigDecimal calcRate(Company company, String duration) {
        if (Company.CreditRating.D.equals(company.getCreditRating())) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.company.creditRating.notEnough");
        }
        return Company.rateMap.get(company.getCreditRating()+"-"+duration);
    }

    public FfLoan findByWaybillId(Long waybillId) {
        return ffLoanRepo.findFirstByWaybillId(waybillId);
    }
}
